package com.tuziki.zk.studio.util;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.log4j.Logger;

import java.io.PrintStream;
import java.lang.reflect.Method;

/**
 * Created by Sannychan on 2015/3/27.
 */
public class PrintStreamProxy implements MethodInterceptor {

    static Logger logger = Logger.getLogger(PrintStreamProxy.class.getName());

    public static PrintStream getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ZKPrintStream.class);
        enhancer.setCallback(new PrintStreamProxy());
        Object obj = null;
        try {
            obj = enhancer.create();
        } catch (Exception e) {
            logger.error(e);
            //e.printStackTrace();
        }

        return (PrintStream) obj;
    }

    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        String methodName = method.getName();
        if ("print".equalsIgnoreCase(methodName) || "println".equalsIgnoreCase(methodName)) {
            logger.info(args[0]);
            return null;
        }
        return methodProxy.invokeSuper(object, args);
    }
}
